package democache;

import democache.computer.Computable;
import democache.computer.ExpensiveFunction;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Brook
 * 用装饰者模式，给计算器自动添加缓存功能
 * 性能差：
 * 当多个线程同时想计算的时候，需要慢慢等待，严重时，
 * 性能甚至比不用缓存差
 * 解决代码侵入问题
 */
public class DemoCache2<A, V> implements Computable<A, V> {

    private final Map<A, V> cache = new HashMap();

    private final Computable<A, V> c;

    public DemoCache2(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public synchronized V compute(A arg) throws Exception {
        System.out.println("进入缓存机制");
        V result = cache.get(arg);
        if(result == null){
            result = c.compute(arg);
            cache.put(arg,result);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        DemoCache2<String, Integer> demoCache2 = new DemoCache2(new ExpensiveFunction());
        Integer result = demoCache2.compute("666");
        System.out.println("第一次计算结果："+result);
        result = demoCache2.compute("666");
        System.out.println("第二次计算结果："+result);
    }
}
